import React, { useState } from 'react';
import {
  Card,
  Table,
  Input,
  Button,
  Space,
  Tag,
  Modal,
  Form,
  Select,
  Row,
  Col,
  DatePicker,
  message,
  Checkbox,
  Divider,
  Tabs,
  Avatar,
} from 'antd';

const { TabPane } = Tabs;
import { useNavigate } from 'react-router-dom';
import {
  SearchOutlined,
  PlusOutlined,
  FileTextOutlined,
  EditOutlined,
  CheckCircleOutlined,
  UserOutlined,
} from '@ant-design/icons';
import Layout from '../../components/Layout';

const { Option } = Select;
const { TextArea } = Input;
const { RangePicker } = DatePicker;

// 模拟患者列表数据
const mockPatients = [
  { id: '1', name: '张三', gender: '男', age: 45, department: '骨科', diagnosis: '膝关节退行性病变', status: '住院' },
  { id: '2', name: '李四', gender: '女', age: 38, department: '骨科', diagnosis: '腰椎间盘突出', status: '门诊' },
  { id: '3', name: '王五', gender: '男', age: 52, department: '骨科', diagnosis: '骨折术后', status: '住院' },
  { id: '4', name: '赵六', gender: '男', age: 28, department: '骨科', diagnosis: '踝关节扭伤', status: '门诊' },
  { id: '5', name: '钱七', gender: '女', age: 60, department: '骨科', diagnosis: '骨质疏松', status: '门诊' },
];

// 模拟检查项目数据
const mockExaminationItems = [
  { id: '1', name: 'X光检查', category: '影像学', price: 120, available: true },
  { id: '2', name: 'CT扫描', category: '影像学', price: 350, available: true },
  { id: '3', name: '核磁共振(MRI)', category: '影像学', price: 800, available: true },
  { id: '4', name: '血常规', category: '血液检查', price: 35, available: true },
  { id: '5', name: '尿常规', category: '体液检查', price: 20, available: true },
  { id: '6', name: '生化全套', category: '血液检查', price: 280, available: true },
  { id: '7', name: '心电图', category: '功能检查', price: 45, available: true },
  { id: '8', name: 'B超检查', category: '影像学', price: 150, available: false },
];

// 模拟检查申请记录
const mockApplications = [
  {
    id: '1',
    patient: '张三',
    patientId: '1',
    items: ['X光检查', '血常规'],
    applyDate: '2024-06-15',
    applyTime: '09:30',
    status: '已完成',
    resultStatus: '已出报告',
    doctor: '王医生',
  },
  {
    id: '2',
    patient: '李四',
    patientId: '2',
    items: ['CT扫描'],
    applyDate: '2024-06-14',
    applyTime: '14:20',
    status: '已预约',
    resultStatus: '待检查',
    doctor: '王医生',
  },
  {
    id: '3',
    patient: '王五',
    patientId: '3',
    items: ['MRI', '生化全套'],
    applyDate: '2024-06-13',
    applyTime: '10:15',
    status: '已完成',
    resultStatus: '已出报告',
    doctor: '王医生',
  },
];

const Examination: React.FC = () => {
  const navigate = useNavigate();
  const [searchText, setSearchText] = useState('');
  const [patients, setPatients] = useState(mockPatients);
  const [filteredPatients, setFilteredPatients] = useState(mockPatients);
  const [applications, setApplications] = useState(mockApplications);
  const [isApplyModalVisible, setIsApplyModalVisible] = useState(false);
  const [selectedPatient, setSelectedPatient] = useState<any>(null);
  const [selectedItems, setSelectedItems] = useState<string[]>([]);
  const [applyDate, setApplyDate] = useState<any>(null);
  const [diagnosis, setDiagnosis] = useState('');
  const [remark, setRemark] = useState('');
  const [form] = Form.useForm();

  // 搜索患者
  const handleSearch = () => {
    const filtered = patients.filter(
      (patient) =>
        patient.name.toLowerCase().includes(searchText.toLowerCase()) ||
        patient.diagnosis.toLowerCase().includes(searchText.toLowerCase())
    );
    setFilteredPatients(filtered);
  };

  // 重置搜索
  const handleReset = () => {
    setSearchText('');
    setFilteredPatients(patients);
  };

  // 打开检查申请模态框
  const handleOpenApplyModal = (patient: any) => {
    setSelectedPatient(patient);
    setSelectedItems([]);
    setDiagnosis(patient.diagnosis);
    setRemark('');
    setApplyDate(null);
    setIsApplyModalVisible(true);
  };

  // 处理检查项目选择
  const handleItemSelect = (checkedValues: string[]) => {
    setSelectedItems(checkedValues);
  };

  // 提交检查申请
  const handleSubmitApplication = () => {
    if (selectedItems.length === 0) {
      message.error('请至少选择一个检查项目');
      return;
    }
    if (!applyDate) {
      message.error('请选择申请日期');
      return;
    }

    const newApplication = {
      id: Date.now().toString(),
      patient: selectedPatient.name,
      patientId: selectedPatient.id,
      items: selectedItems,
      applyDate: applyDate.format('YYYY-MM-DD'),
      applyTime: new Date().toLocaleTimeString('zh-CN', { hour12: false }).slice(0, 5),
      status: '已预约',
      resultStatus: '待检查',
      doctor: '王医生',
    };

    setApplications([newApplication, ...applications]);
    setIsApplyModalVisible(false);
    message.success('检查申请提交成功');
  };

  // 查看检查报告
  const handleViewReport = (application: any) => {
    message.info('查看检查报告功能开发中');
  };

  // 患者表格列定义
  const patientColumns = [
    {
      title: '患者姓名',
      dataIndex: 'name',
      key: 'name',
      sorter: (a: any, b: any) => a.name.localeCompare(b.name),
    },
    {
      title: '性别',
      dataIndex: 'gender',
      key: 'gender',
      width: 60,
    },
    {
      title: '年龄',
      dataIndex: 'age',
      key: 'age',
      width: 60,
    },
    {
      title: '科室',
      dataIndex: 'department',
      key: 'department',
      width: 80,
    },
    {
      title: '诊断',
      dataIndex: 'diagnosis',
      key: 'diagnosis',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 80,
      render: (status: string) => (
        <Tag color={status === '住院' ? 'blue' : 'green'}>{status}</Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Button
          type="primary"
          size="small"
          icon={<PlusOutlined />}
          onClick={() => handleOpenApplyModal(record)}
        >
          申请检查
        </Button>
      ),
      width: 100,
    },
  ];

  // 申请记录表格列定义
  const applicationColumns = [
    {
      title: '申请编号',
      dataIndex: 'id',
      key: 'id',
      width: 100,
    },
    {
      title: '患者信息',
      dataIndex: 'patient',
      key: 'patient',
      render: (patient: string) => (
        <Space>
          <Avatar icon={<UserOutlined />} />
          <span>{patient}</span>
        </Space>
      ),
    },
    {
      title: '检查项目',
      dataIndex: 'items',
      key: 'items',
      render: (items: string[]) => (
        <Space wrap>
          {items.map((item, index) => (
            <Tag key={index} color="blue">{item}</Tag>
          ))}
        </Space>
      ),
    },
    {
      title: '申请日期',
      dataIndex: 'applyDate',
      key: 'applyDate',
      width: 100,
    },
    {
      title: '申请时间',
      dataIndex: 'applyTime',
      key: 'applyTime',
      width: 80,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 80,
      render: (status: string) => (
        <Tag color={
          status === '已完成' ? 'success' : 
          status === '已预约' ? 'processing' : 
          status === '已取消' ? 'default' : 'warning'
        }>
          {status}
        </Tag>
      ),
    },
    {
      title: '报告状态',
      dataIndex: 'resultStatus',
      key: 'resultStatus',
      width: 100,
      render: (resultStatus: string) => (
        <Tag color={
          resultStatus === '已出报告' ? 'green' : 
          resultStatus === '待检查' ? 'processing' : 
          resultStatus === '检查中' ? 'warning' : 'default'
        }>
          {resultStatus}
        </Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Button
          type="link"
          icon={<FileTextOutlined />}
          disabled={record.resultStatus !== '已出报告'}
          onClick={() => handleViewReport(record)}
        >
          查看报告
        </Button>
      ),
      width: 100,
    },
  ];

  return (
    <Layout title="检查申请" showBackButton>
      <Tabs defaultActiveKey="1" type="card">
        {/* 患者列表 */}
        <TabPane tab="患者列表" key="1">
          <Card>
            {/* 搜索栏 */}
            <Row gutter={16} style={{ marginBottom: 16 }}>
              <Col flex="auto">
                <Space>
                  <Input
                    placeholder="搜索患者姓名或诊断"
                    value={searchText}
                    onChange={(e) => setSearchText(e.target.value)}
                    prefix={<SearchOutlined />}
                    onPressEnter={handleSearch}
                    style={{ width: 300 }}
                  />
                  <Button type="primary" onClick={handleSearch}>搜索</Button>
                  <Button onClick={handleReset}>重置</Button>
                </Space>
              </Col>
            </Row>

            {/* 患者表格 */}
            <Table
              columns={patientColumns}
              dataSource={filteredPatients}
              rowKey="id"
              pagination={{ pageSize: 10 }}
            />
          </Card>
        </TabPane>

        {/* 申请记录 */}
        <TabPane tab="申请记录" key="2">
          <Card>
            <Table
              columns={applicationColumns}
              dataSource={applications}
              rowKey="id"
              pagination={{ pageSize: 10 }}
            />
          </Card>
        </TabPane>
      </Tabs>

      {/* 检查申请模态框 */}
      <Modal
        title={`为患者 ${selectedPatient?.name} 申请检查`}
        open={isApplyModalVisible}
        onOk={handleSubmitApplication}
        onCancel={() => setIsApplyModalVisible(false)}
        width={700}
      >
        <Form layout="vertical">
          <Row gutter={16}>
            <Col span={24}>
              <Form.Item label="患者信息">
                <Card>
                  <Row gutter={16}>
                    <Col span={6}>
                      <div><strong>姓名：</strong>{selectedPatient?.name}</div>
                    </Col>
                    <Col span={6}>
                      <div><strong>性别：</strong>{selectedPatient?.gender}</div>
                    </Col>
                    <Col span={6}>
                      <div><strong>年龄：</strong>{selectedPatient?.age}岁</div>
                    </Col>
                    <Col span={6}>
                      <div><strong>科室：</strong>{selectedPatient?.department}</div>
                    </Col>
                  </Row>
                </Card>
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={24}>
              <Form.Item label="临床诊断">
                <TextArea
                  rows={2}
                  value={diagnosis}
                  onChange={(e) => setDiagnosis(e.target.value)}
                  placeholder="请输入临床诊断"
                />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={24}>
              <Form.Item label="选择检查项目">
                <Checkbox.Group onChange={handleItemSelect}>
                  <Row gutter={[16, 16]}>
                    {mockExaminationItems.map((item) => (
                      <Col xs={12} sm={8} md={6} key={item.id}>
                        <Checkbox
                          value={item.name}
                          disabled={!item.available}
                        >
                          <span>
                            {item.name} ({item.category})
                            <Tag 
                              color={!item.available ? 'default' : 'blue'} 
                              style={{ marginLeft: 8, fontSize: 12 }}
                            >
                              ¥{item.price}
                              {!item.available && <span style={{ marginLeft: 4 }}>(不可用)</span>}
                            </Tag>
                          </span>
                        </Checkbox>
                      </Col>
                    ))}
                  </Row>
                </Checkbox.Group>
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item label="申请日期">
                <DatePicker
                  value={applyDate}
                  onChange={(date) => setApplyDate(date)}
                  style={{ width: '100%' }}
                  placeholder="请选择申请日期"
                />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={24}>
              <Form.Item label="备注">
                <TextArea
                  rows={3}
                  value={remark}
                  onChange={(e) => setRemark(e.target.value)}
                  placeholder="请输入备注信息"
                />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>
    </Layout>
  );
};

export default Examination;